package es.uniovi.miw.tfm.scowt.web.controller;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import es.uniovi.miw.tfm.scowt.api.CompetenceService;
import es.uniovi.miw.tfm.scowt.model.Competence;
import es.uniovi.miw.tfm.scowt.web.perso.ComboObject;
import es.uniovi.miw.tfm.scowt.web.perso.CompetencePersoModel;

/**
 * 
 * @author Alejandro Alvarez
 * 
 */
public class CompetenciesController extends SimpleFormController {

    private Log logger = LogFactory.getLog(getClass());

    @Autowired
    private CompetenceService service;

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
	    throws Exception {
	logger.info("Returning competencies view");
	// Prepare the model response
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addObject("model", createModel());
	return modelAndView;
    }

    private CompetencePersoModel createModel() {
	CompetencePersoModel model = new CompetencePersoModel();
	// Call the Service
	List<Competence> competencies = service.getAllCompetencies();
	//Fill the Comboboxes and return the result
	model.setCompetencies(fillCompetenciesCombo(competencies));
	return model;
    }

    private List<ComboObject> fillCompetenciesCombo(List<Competence> competencies) {
	List<ComboObject> competenciesCombo = new LinkedList<ComboObject>();
	boolean isFirst = true;
	for(Competence competence : competencies){
	    ComboObject option = new ComboObject();
	    option.setLabel(competence.getTitle());
	    option.setValue(Long.toString(competence.getId()));
	    if(isFirst){
		option.setSelected(true);
		isFirst = false;
	    } else{
		option.setSelected(false);
	    }
	    competenciesCombo.add(option);
	}
	return competenciesCombo;
    }
    
}
